import React from 'react';
import { Modal, Tree } from 'antd';
import { useEffect } from 'react';
import { useState } from 'react';
import API from '@/api/xjindex.js';

const filterUserList = (data) => {};
const userModal = ({ visible, onCreate, onCancel, checkedIds }) => {
  const [userList, setUserList] = useState(null);
  const [checkIds, setCheckIds] = useState([]);
  const [ids, setIds] = useState([]);

  const initUserList = () => {
    API.showUser().then((res) => {
      if (res?.t) {
        let treeData = res.t.filter((x) => {
          x.treeName = x.name;
          x.treeId = x.id;
          if (x.userList) {
            x.userList.forEach((y) => {
              y.treeName = y.userName;
              y.treeId = `${y.id}-${y.userId}`;
            });
          }
          return x.userList;
        });
        setUserList(treeData);
      }
    });
  };
  const fieldNames = { title: 'name', key: 'id', children: 'children' };

  function lookForId(data = [], arr = []) {
    for (let item of data) {
      if (item.children && item.children.length) {
        lookForId(item.children, arr);
      } else {
        arr.push(item.id);
      }
    }
    return arr;
  }

  function lookForAllId(data = [], arr = []) {
    for (let item of data) {
      arr.push(item.id);
      if (item.children && item.children.length) {
        lookForAllId(item.children, arr);
      }
    }
    return arr;
  }

  useEffect(() => {
    initUserList();
    // console.log(checkedIds);
    // setCheckIds(lookForId(checkedIds));
    // setIds(lookForAllId(checkedIds));
  }, []);

  useEffect(() => {
    // console.log(checkedIds);
    setCheckIds(checkedIds);
    setIds(lookForAllId(checkedIds));
  }, [visible]);

  const onCheck = (checkedKeys, e) => {
    setCheckIds(checkedKeys);
    setIds([...checkedKeys, ...e.halfCheckedKeys]);
  };

  return (
    <Modal
      visible={visible}
      title="选择接受人员"
      okText="确定"
      cancelText="取消"
      onCancel={onCancel}
      maskClosable={false}
      destroyOnClose
      onOk={() => {
        onCreate({ ids, userList });
      }}
    >
      <Tree
        checkable
        treeData={userList}
        fieldNames={fieldNames}
        checkedKeys={checkIds}
        fieldNames={{
          children: 'userList',
          title: 'treeName',
          key: 'treeId',
        }}
        onCheck={onCheck}
      />
    </Modal>
  );
};

export default userModal;
